/* Copyright (c) 2015,2016 Lucky Byte, Inc.
 */
package com.lucky_byte.pay.jar;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import freemarker.template.TemplateMethodModelEx;
import freemarker.template.TemplateModel;
import freemarker.template.TemplateModelException;
import freemarker.template.utility.DeepUnwrap;

/**
 * 从 FreeMarker 通过 JDBC 查询数据表
 */
public class FMJdbcListBy implements TemplateMethodModelEx
{
	private static final Logger logger = LogManager.getLogger();

	@Override
	@SuppressWarnings({ "rawtypes" })
	public Object exec(List args) throws TemplateModelException {
		if (args.size() < 2) {
			logger.error("listby 方法需要至少 2 个参数，"
					+ "用法[listby(table_name, cond_clause, ...)].");
			return null;
		}
		String table_name = (String) DeepUnwrap.unwrap(
				(TemplateModel) args.get(0));
		String clause = (String) DeepUnwrap.unwrap(
				(TemplateModel) args.get(1));
		try {
			List<Object> params = new ArrayList<>();
			for (int i = 2; i < args.size(); i++) {
				params.add(DeepUnwrap.unwrap((TemplateModel) args.get(i)));
			}
			JdbcTable table = JdbcTable.listBy(table_name, clause, params);
			List<Object> records = new ArrayList<>();
			for (int i = 0; i < table.getRecordCount(); i++) {
				records.add(new FMJdbcRecord(table.getRecord(i)));
			}
			return records;
		} catch (SQLException e) {
			logger.error("查询[{}]错误[{}].", table_name, e.getMessage());
			return new ArrayList<>();
		}
	}

}
